package ImageHandleModel

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

const (
	ApiKey = "sk-0ad14d234ede4a8cad3d76e5e8136ff0"
	URL    = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions" // WebSocket服务器地址
)

// 定义请求结构体
type OCRRequest struct {
	Model    string    `json:"model"`
	Messages []Message `json:"messages"`
}

type Message struct {
	Role    string    `json:"role"`
	Content []Content `json:"content"`
}

type Content struct {
	Type      string    `json:"type"`
	ImageURL  *ImageURL `json:"image_url,omitempty"`
	Text      string    `json:"text,omitempty"`
	MinPixels int       `json:"min_pixels,omitempty"`
	MaxPixels int       `json:"max_pixels,omitempty"`
}

type ImageURL struct {
	URL string `json:"url"`
}

// 定义响应结构体
type OCRResponse struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Created int64  `json:"created"`
	Model   string `json:"model"`
	Choices []struct {
		Index   int `json:"index"`
		Message struct {
			Role    string `json:"role"`
			Content string `json:"content"`
		} `json:"message"`
	} `json:"choices"`
	Usage struct {
		PromptTokens     int `json:"prompt_tokens"`
		CompletionTokens int `json:"completion_tokens"`
		TotalTokens      int `json:"total_tokens"`
	} `json:"usage"`
}

func qwenVlOcr(base64Image string) string {
	// 构建请求数据
	requestData := OCRRequest{
		Model: "qwen-vl-ocr-latest",
		Messages: []Message{
			{
				Role: "user",
				Content: []Content{
					{
						Type:      "image_url",
						ImageURL:  &ImageURL{URL: fmt.Sprintf("data:image/jpeg;base64,%s", base64Image)},
						MinPixels: 28 * 28 * 4,
						MaxPixels: 28 * 28 * 8192,
					},
				},
			},
		},
	}

	// 转换请求数据为JSON
	jsonData, err := json.Marshal(requestData)
	if err != nil {
		fmt.Printf("JSON序列化错误: %v\n", err)
		return ""
	}

	// 创建HTTP客户端
	client := &http.Client{}
	req, err := http.NewRequest("POST", URL, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("创建请求错误: %v\n", err)
		return ""
	}

	// 设置请求头
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", ApiKey))

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("发送请求错误: %v\n", err)
		return ""
	}
	defer resp.Body.Close()

	// 读取响应
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("读取响应错误: %v\n", err)
		return ""
	}

	// 检查HTTP状态码
	if resp.StatusCode != http.StatusOK {
		fmt.Printf("请求失败，状态码: %d, 响应: %s\n", resp.StatusCode, string(respBody))
		return ""
	}

	// 解析响应
	var ocrResp OCRResponse
	err = json.Unmarshal(respBody, &ocrResp)
	if err != nil {
		fmt.Printf("解析响应错误: %v, 原始响应: %s\n", err, string(respBody))
		return ""
	}

	// 输出结果
	if len(ocrResp.Choices) > 0 {
		return ocrResp.Choices[0].Message.Content
	} else {
		fmt.Println("未获取到识别结果")
	}
	return ""
}
